<template>
  <div class="org">
    <div
      style="margin-bottom: 10px; display: flex; justify-content: space-between"
    >
      <div style="float: left">
        <el-button
          v-permission="'company_organizational_employee_create'"
          type="primary"
          plain
          @click="handleClickAdd"
          data-tracker="P37-5"
        >
          <i class="el-icon-plus"></i> 新增员工
        </el-button>
        <el-button
          v-permission="'company_organizational_employee_delete'"
          type="danger"
          plain
          @click="handleClickDelete"
          data-tracker="P37-6"
        >
          <i class="el-icon-delete"></i>
          删除员工
        </el-button>
      </div>
      <div style="float: right">
        <el-pagination
          background
          small
          :current-page="oPaginations.pageIndex"
          :page-sizes="oPaginations.pageSizes"
          :page-size="oPaginations.pageSize"
          :layout="oPaginations.layout"
          :total="oPaginations.total"
          @size-change="handleOrgSizeChange"
          @current-change="handleOrgCurrentChange"
        />
      </div>
    </div>
    <el-table
      border
      stripe
      :data="staffList"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />

      <el-table-column prop="name" label="姓名" width="150" />
      <el-table-column prop="gender" label="性别" width="100">
        <template slot-scope="scope">
          {{ ["男", "女"][scope.row.gender] }}
        </template>
      </el-table-column>
      <el-table-column prop="mobile" label="手机" width="180" />
      <el-table-column prop="user" label="用户名" width="220" />

      <el-table-column prop="status" label="状态" width="150">
        <template slot-scope="scope">
          {{ ["启用", "禁用"][scope.row.status] }}
        </template>
      </el-table-column>
      <el-table-column prop="id_card" label="身份证" width="220" />
      <el-table-column prop="position" label="职位" width="150" />
      <el-table-column prop="branch_name" label="所在组织" width="220" />
      <el-table-column prop="remark" label="备注" width="380" />
      <el-table-column label="操作" align="center" width="120" fixed="right">
        <template slot-scope="scope">
          <el-button
            v-permission="'company_organizational_employee_detail'"
            size="small"
            type="text"
            data-tracker="P37-7"
            @click="handleClick(scope.row, 'detail')"
            >查看</el-button
          >
          <el-button
            v-permission="'company_organizational_employee_update'"
            size="small"
            type="text"
            data-tracker="P37-8"
            @click="handleClick(scope.row, 'edit')"
            >编辑</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <el-drawer
      size="40%"
      ref="perForm"
      :title="`${showText}`"
      :before-close="handleCloseDialog"
      :direction="direction"
      :visible.sync="showOrgDialog"
      v-if="showOrgDialog"
      :wrapperClosable="false"
    >
      <!-- 表单 -->
      <el-form
        ref="ruleform"
        label-width="100px"
        :model="formData"
        :rules="rules"
        :inline="true"
        class="ruleForm"
        :disabled="mode === 'detail'"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="formData.name" style="width: 240px" />
        </el-form-item>
        <el-form-item label="所属组织" prop="branch_id">
          <el-cascader
            :options="branchData"
            :show-all-levels="false"
            v-model="formData.branchIds"
            :props="{
              checkStrictly: true,
              label: 'branch_name',
              value: 'id',
              children: 'next_level_data',
            }"
            clearable
            style="width: 240px"
          >
          </el-cascader>
        </el-form-item>
        <el-form-item label="性别" prop="gender" style="width: 340px">
          <el-radio v-model="formData.gender" label="0">男</el-radio>
          <el-radio v-model="formData.gender" label="1">女</el-radio>
        </el-form-item>
        <el-form-item label="用户账号" prop="user">
          <el-input
            :disabled="mode === 'edit'"
            v-model="formData.user"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="formData.mobile" style="width: 240px" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="mode === 'add'">
          <el-input
            show-password
            v-model="formData.password"
            autoComplete="new-password"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item label="身份证" prop="id_card">
          <el-input v-model="formData.id_card" style="width: 240px" />
        </el-form-item>
        <el-form-item label="角色" prop="role_id">
          <el-select
            multiple
            v-model="formData.role_id"
            placeholder="请选择"
            style="width: 240px"
          >
            <el-option
              v-for="item in roleList"
              :label="item.name"
              :value="item.id"
              :key="item.id + ''"
              >{{ item.name }}</el-option
            >
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="属性" prop="property">
          <el-select v-model="formData.property" placeholder="请选择属性">
            <el-option v-for="(item) in property" :label="item.value" :value="item.id" :key="item.value">{{
                item.value
            }}</el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="职位" prop="position">
          <el-input v-model="formData.position" style="width: 240px" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
            v-model="formData.status"
            placeholder="请选择状态"
            style="width: 240px"
          >
            <el-option
              v-for="item in status"
              :label="item.value"
              :value="item.id"
              :key="item.value"
              >{{ item.value }}</el-option
            >
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="备注" prop="description">
          <el-input v-model="formData.remark" style="width:100%" />
        </el-form-item> -->
      </el-form>
      <!-- 操作按钮 -->
      <el-row type="flex" justify="center" class="footer_flex_b">
        <el-col :span="8">
          <el-button
            :data-tracker="mode === 'add' ? 'P37-12' : 'P37-16'"
            @click="handleCloseDialog"
            >取消</el-button
          >
          <el-button
            type="primary"
            :data-tracker="mode === 'add' ? 'P37-11' : 'P37-15'"
            @click="handleClickOk"
            >确定</el-button
          >
        </el-col>
      </el-row>
    </el-drawer>
  </div>
</template>
<script>
import {
  staffListData,
  updateStaff,
  newLystaff,
  queryStaff,
  removeStaff,
  roleBox,
  peopleRole,
  UserCount,
  mobileCount,
  organizationBox,
} from "@/api/organization";
import AreaJson from "@/assets/datas/area.json";
import { Types, Propertys, Status } from "../constant";
import md5 from "js-md5";
const initData = () => {
  return { status: "0" };
};
export default {
  name: "organization",
  data() {
    return {
      showOrgDialog: false,
      formData: {
        branch_id: this.currentOrgInfo.id,
        status: "0",
        gender: "",
      },
      areaData: [],
      // 部门分页
      oPaginations: {
        pageIndex: 1, // 当前位于哪页
        pageSize: 5, // 1页显示多少条
        pageSizes: [5, 10, 15, 20], //每页显示多少条
        total: 0,
        layout: "total, sizes, prev, pager, next, jumper", // 翻页属性
      },
      rules: {
        gender: [{ required: true, message: "请选择性别", trigger: "blur" }],
        user: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            validator: this.checkUser,
            trigger: "blur",
          },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          {
            validator: this.checkMobile,
            trigger: "blur",
          },
        ],
        password: [
          {
            required: true,
            pattern: /^(?=.*[0-9].*)(?=.*[A-Za-z].*).{6,18}$/,
            message: "密码6-18位字符，至少含1个字母",
            trigger: "blur",
          },
        ],
        role_id: [{ required: true, message: "请选择角色", trigger: "change" }],
        position: [
          { required: true, message: "请输入员工职位", trigger: "blur" },
        ],
        status: [{ required: true, message: "请选择状态", trigger: "change" }],
      },
      staffList: [],
      roleList: [],
      branchData: [],
      mode: "",
    };
  },
  computed: {
    showText() {
      const { mode } = this;
      if (mode === "add") {
        return "新增员工";
      } else if (mode === "edit") {
        return "编辑员工";
      } else if (mode === "detail") {
        return "员工详情";
      }
    },
  },
  props: ["currentOrgInfo"],
  watch: {
    currentOrgInfo: function (newV) {
      this.getStaffList();
    },
  },
  created() {
    this.areaData = AreaJson;
    this.types = Types;
    this.propertys = Propertys;
    this.status = Status;
    this.property = [
      { id: "0", value: "员工" },
      { id: "1", value: "客户" },
    ];
  },
  mounted() {
    this.getRoleBox();
    organizationBox().then((res) => {
      this.branchData = res.data;
    });
  },
  filters: {},
  methods: {
    handleClose() {
      this.$emit("parentFlagShow", false);
    },
    getParentIds(id, data) {
      function backtrack(data, id, parents) {
        for (let i = 0; i < data.length; i++) {
          const item = data[i];
          // (1)找到id则返回父级id
          if (item.id === id) return parents;
          // (2)判断是否要递归
          if (!item.next_level_data || !item.next_level_data.length) continue;
          // (3)递归前当前id入栈
          parents.push(item.id);
          //(4)如果递归找到id，则返回父级id
          if (backtrack(item.next_level_data, id, parents).length)
            return parents;
          // (5)如果递归没找到，当前id出栈
          parents.pop();
        }
        return [];
      }
      return backtrack(data, id, []);
    },
    // 检查用户名是否重复
    checkUser(rule, val, cb) {
      if (this.mode === "add") {
        UserCount({ username: val }).then((res) => {
          if (res.data.count > 0) {
            cb(new Error("用户名已存在"));
          } else {
            cb();
          }
        });
      }
    },
    checkMobile(rule, val, cb) {
      mobileCount({ mobile: val }).then((res) => {
        if (res.data > 0) {
          cb(new Error("手机号已绑定"));
        } else {
          cb();
        }
      });
    },
    // 新增员工
    handleClickAdd() {
      this.formData = initData();
      this.formData.branch_id = this.currentOrgInfo.id;
      this.formData.branchIds = this.getParentIds(
        this.formData.branch_id,
        this.branchData
      ).concat(this.formData.branch_id);
      this.mode = "add";
      this.showOrgDialog = true;
    },
    // 点击确定 新增/查看/编辑
    async handleClickOk() {
      this.formData.branch_id = this.formData.branchIds.slice(-1) + "";
      this.formData.user = this.formData.user.trim();
      this.formData.role_name = this.roleList
        .filter((item) => this.formData.role_id.includes(item.id))
        .map((i) => {
          return i.name;
        });

      if (this.mode === "detail") {
        this.showOrgDialog = false;
        return;
      } else if (this.mode === "edit") {
        updateStaff(this.formData).then((res) => {
          if (res.code === 10000) {
            this.$message({
              type: "success",
              message: "修改成功!",
            });
            this.showOrgDialog = false;
            this.getStaffList();
          } else {
            this.$message({
              type: "warning",
              message: res.message,
            });
          }
        });
      }
      this.$refs.ruleform.validate((valid) => {
        if (!valid) return;
        // 查看
        if (this.mode === "add") {
          const _formData = { ...this.formData };
          _formData.password = md5(this.formData.password);
          newLystaff(_formData).then((res) => {
            if (res.code === 10000) {
              this.$message({
                type: "success",
                message: "新建成功!",
              });
              this.showOrgDialog = false;
              this.getStaffList();
            } else {
              this.$message({
                type: "warning",
                message: res.message,
              });
            }
          });
        }
      });
    },
    // 关闭弹框
    handleCloseDialog() {
      this.showOrgDialog = false;
    },
    // 选中id变化
    handleSelectionChange(val) {
      this.deleteParams = val.map((item) => item.id);
      // console.log(this.deleteParams);
    },
    handleClickDelete() {
      if (this.deleteParams.length === 0) {
        this.$message({
          message: "选中后可继续进行操作",
          type: "error",
        });
        return;
      }
      this.$confirm("确定要删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          removeStaff({ id: this.deleteParams }).then((res) => {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.getStaffList();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    handleClick({ id }, mode) {
      this.mode = mode;
      queryStaff({ id }).then((res) => {
        if (res.code === 10000) {
          this.formData = res.data;
          this.formData.branch_id = this.currentOrgInfo.id;
          this.formData.branchIds = this.getParentIds(
            this.formData.branch_id,
            this.branchData
          ).concat(this.formData.branch_id);
          this.showOrgDialog = true;
        }
      });
    },
    addmangerFN() {
      this.showOrgDialog = true;
    },
    handleAddrChange(val) {
      [
        this.formData.province_id,
        this.formData.city_id,
        this.formData.district_id,
      ] = val;
    },
    handleOrgCurrentChange(val) {
      // console.log(`当前页: ${val}`);
    },
    handleOrgCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.oPaginations.pageIndex = val;
      this.getStaffList();
    },
    handleOrgSizeChange(val) {
      this.oPaginations.pageSize = val;
      this.getStaffList();
    },
    handleStaffCurChange(val) {
      // console.log(`当前页: ${val}`);
    },
    clcikShowFn(val) {
      // console.log(val.paneName, 11111111);
    },
    // 员工列表
    getStaffList() {
      if (typeof this.currentOrgInfo.id === "undefined") {
        return;
      }
      staffListData({
        branch_id: String(this.currentOrgInfo.id),
        page: this.oPaginations.pageIndex,
        page_size: this.oPaginations.pageSize,
      }).then((res) => {
        this.staffList = res.data.list;
        this.oPaginations.total = res.data.pagination.total;
      });
    },
    getRoleBox() {
      roleBox().then((res) => {
        const data = res.data || [];
        this.roleList = data;
        // 员工角色不要司机
        // this.roleList = data.filter(item=>!(item.name==='司机'));
      });
    },
  },
};
</script>
<style lang="less" scoped>
.footer_flex_b {
  width: 40%;
  text-align: center;
  position: fixed;
  bottom: 30px;
}
</style>
